package com.mrs.filter;

import com.alibaba.fastjson.JSON;
import com.mrs.common.ResponseResult;
import com.mrs.common.enums.AppHttpCodeEnum;
import com.mrs.entity.LoginUser;
import com.mrs.utils.JwtUtil;
import com.mrs.utils.RedisCache;
import com.mrs.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * description: JwtAuthenticationTokenFilter
 * date: 2022/8/8 12:15
 * author: MR.孙
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取请求头中的token
        String token = request.getHeader("token");

        if(!StringUtils.hasText(token)){
            //如果请求头中没有token,说明该接口不需要登录,直接放行,让可以执行后面的过滤器
            filterChain.doFilter(request,response);
            return ;

        }

        //从token中解析获取userid
        Claims claims =null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常说明token超时或者token被篡改(非法)
            //抛出异常信息,响应告诉前端需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return ;
        }

        //从redis中获取用户信息
        String userId = claims.getSubject();
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        //判断redis中是否有用户信息
        if(Objects.isNull(loginUser)){

            //没有获取到说明登录过期,提示重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return ;

        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);

    }
}
